import Konva from 'konva'
import { useState } from 'react'
import { Circle, Layer, Stage } from 'react-konva'

function generateItems() {
  const items = []
  for (let i = 0; i < 10; i++) {
    items.push({
      x: Math.random() * window.innerWidth,
      y: Math.random() * window.innerHeight,
      id: 'node-' + i,
      color: Konva.Util.getRandomColor()
    })
  }
  return items
}

export default function View() {
  const [genItems, setGenItems] = useState(generateItems())

  const handleDragStart = e => {
    const id = e.target.name()
    const items = genItems.slice()
    const item = items.find(i => i.id === id)
    const index = items.indexOf(item)
    // remove from the list:
    items.splice(index, 1)
    // add to the top
    items.push(item)
    setGenItems(items)
  }

  const handleDragEnd = e => {
    const id = e.target.name()
    const items = genItems.slice()
    const item = genItems.find(i => i.id === id)
    const index = genItems.indexOf(item)
    // update item position
    items[index] = {
      ...item,
      x: e.target.x(),
      y: e.target.y()
    }
    setGenItems(items)
  }

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        {genItems.map(item => (
          <Circle
            key={item.id}
            name={item.id}
            draggable
            x={item.x}
            y={item.y}
            fill={item.color}
            radius={50}
            onDragStart={handleDragStart}
            onDragEnd={handleDragEnd}
          />
        ))}
      </Layer>
    </Stage>
  )
}
